# MirrorOS Makefile
# Copyright 2008 Matthew Iselin

# location where the kernel binary is installed
INSTALL_FOLDER:=./binary/

# compiler and flags
CC:=/usr/mattise/cross/bin/i586-pc-mattise-gcc
CFLAGS:=-I ./include -nostdlib -ffreestanding -O0 -Werror -Wall -Wextra -Wredundant-decls -Wshadow -Wpointer-arith -Wcast-align -Wwrite-strings -Wnested-externs -Winline -Wno-long-long

# linker and flags
LD:=/usr/mattise/cross/bin/i586-pc-mattise-ld
LDFLAGS:=-T ./link.ld -Map link.map -o
LDSFLAGS:=-T ./link.ld -Map link.map -shared -o

# project directories
PROJDIRS:=. core mem screen kernio string process exec devman syscalls message vfs ramfs net net/ne2k
# net

# assembler
AS:=/usr/mattise/cross/bin/i586-pc-mattise-as
AS_SRCS:=loader.asm

# nm binary
NM:=/usr/mattise/cross/bin/i586-pc-mattise-nm

# objdump binary
OBJDUMP:=/usr/mattise/cross/bin/i586-pc-mattise-objdump

# source and objects, and final binary
SRCS:=$(shell find $(PROJDIRS) -maxdepth 1 -name "*.c" -type f)
OBJS:=$(patsubst %.asm,%.o,$(AS_SRCS)) $(patsubst %.c,%.o,$(SRCS))

# echo command location
ECHO:=echo

# dependiencies
DEPFILES:=$(patsubst %.c,%.d,$(SRCS))
ASDEPFILES:=$(patsubst %.asm,%.d,$(AS_SRCS))

# final binary filename
FINALBIN:=$(INSTALL_FOLDER)kernel.bin
FINALSBIN:=$(INSTALL_FOLDER)kernel.so
SYMBOL_MAP:=$(INSTALL_FOLDER)symbols.map
DISASSEMBLY:=$(INSTALL_FOLDER)kernel.asm

# target all builds the kernel
all: $(FINALBIN)

# install copies the binary to the install folder
install: $(FINALBIN)
	# TODO: make_ramfs should be a bash shell script for portability
	(cd ../; make_ramfs.bat)
	cp binary/kernel.bin b:/boot/kernel.bin
	cp binary/ramfs.bin b:/boot/ramfs.bin

# clean up, but don't remove the binary from the install folder
clean:
	rm $(shell find -iname "*.[oda]")
	rm $(FINALBIN)

# tests the system
test: $(FINALBIN)
	(cd ./binary;./run.bat;cd ..)

# tests the system, in debug mode
testd: $(FINALBIN)
	(cd ./binary;./rund.bat;cd ..)

# final binary target
$(FINALBIN) : $(OBJS)
	$(LD) $(LDFLAGS) $(FINALBIN) $(OBJS)
	($(NM) $(FINALBIN) | grep -v '\(compiled\)\|\(\.o$$\)\|\( [aUw] \)\|\(\.\.ng$$\)\|\(LASH[RL]DI\)' | sort > $(SYMBOL_MAP))
	($(OBJDUMP) -S -d $(FINALBIN) > $(DISASSEMBLY))

# setup the dependencies (so that header changes update relevant source)
-include $(DEPFILES)

# c++ source files
%.o : %.c
	$(CC) $(CFLAGS) -MMD -MP -MT "$*.d" -c $< -o $@

# assembly
%.o : %.asm
	$(AS) $< -o $@
